/**
 * @title: RouteLocatorService
 * @projectName mscloud
 * @Description TODO
 * @Author
 * @Date 2022/3/18 14:16
 */
package com.atguigu.springcloud.cloudsentinelgatewaydevelop.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
//@Service
public class RouteLocatorService implements RouteLocator, ApplicationEventPublisherAware {
    @Autowired
    RouteLocatorBuilder routeLocatorBuilder;

    ApplicationEventPublisher publisher;
    ArrayList<Route> cache=new ArrayList<>();
    @Override
    public Flux<Route> getRoutes() {
        return Flux.fromIterable(cache);
    }

    public Boolean setRoute(){
        routeLocatorBuilder.routes().route("test",
                p -> p.path("/test4")
                        .uri("http://localhost:8080/test4/")
        ).build().getRoutes().collectList().subscribe(
                routes -> {
                    for(Route route:routes){
                        if(!cache.contains(route)){
                            cache.add(route);
                        }
                    }
                    publisher.publishEvent(new RefreshRoutesEvent(this));
                }
        );
        return true;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        publisher=applicationEventPublisher;
    }
}
